package com.example.mine.user

import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import com.blankj.utilcode.util.ToastUtils
import com.example.mine.R
import com.example.mine.databinding.ActivityCodeLoginBinding
import com.example.mine.viewmodel.UserViewModel
import com.therouter.TheRouter
import com.therouter.router.Route
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
@AndroidEntryPoint
@Route(path = "mine/user/CodeLoginActivity")
class CodeLoginActivity : AppCompatActivity() {
    private val userModel:UserViewModel by viewModels()
    private lateinit var binding: ActivityCodeLoginBinding
    private val operatorType="2"
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding= ActivityCodeLoginBinding.inflate(layoutInflater)
        setContentView(binding.root)
        TheRouter.inject(this)
        initView()
        setupSystemUi()
    }

    private fun initView(){
        binding.mineUserCodeBtn.setOnClickListener {
            requestSendCode()
        }
        binding.mineUserCodeUserPwaLogin.setOnClickListener {
            TheRouter.build("mine/user/AccountLoginActivity").navigation()
        }
    }

    private fun setupSystemUi() {
        lifecycleScope.launch {
            userModel.userState.collect{res->
                when(res.code){
                  200->
                      res.data?.let {
                          TheRouter.build("mine/user/SendCodeActivity").navigation()
                      }
                    else->{
                        Toast.makeText(this@CodeLoginActivity, res.message, Toast.LENGTH_SHORT).show()
                        Log.d("TAG", "setupSystemUi: ${res.message}")
                    }
                }

            }
        }
    }

    private fun requestSendCode() {
        val phone = binding.mineUserEtCodePhone.text.toString()
        ToastUtils.showLong(phone)
        if (phone.isBlank()) {
            Toast.makeText(this, "请输入手机号", Toast.LENGTH_SHORT).show()
            return
        }
        userModel.loadHome(operatorType,phone)

    }


}